#include "webrtc_test.hpp"

using nlohmann::json;
using std::shared_ptr;

// 全局变量用于信号处理
std::atomic<bool> g_running(true);
WebRTC_offer* g_webrtc_client = nullptr;

// 构造函数
WebRTC_offer::WebRTC_offer() : heartbeat_running_(false), robot_id_("ROBOT_001"), ice_gathering_complete_(false) {
    std::cout << "WebRTC_offer 对象已创建" << std::endl;
    // 初始化点云指针
    point_cloud_ = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>);
    // 不在此处初始化WebRTC
}

// 析构函数
WebRTC_offer::~WebRTC_offer() {
    stop_heartbeat();
    std::cout << "WebRTC_offer 对象已销毁" << std::endl;
}

// HTTP响应回调函数
size_t WebRTC_offer::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    size_t total_size = size * nmemb;
    std::string* response = static_cast<std::string*>(userp);
    response->append(static_cast<char*>(contents), total_size);
    return total_size;
}

// 获取房间ID的函数实现
std::string WebRTC_offer::get_room_id() {
    CURL* curl;
    CURLcode res;
    std::string response_string;

    curl = curl_easy_init();
    if (curl) {
        // 设置URL
        curl_easy_setopt(curl, CURLOPT_URL, "https://information-channel.cn/frontend/back-end/rt-webrtc/webrtc/create-room");
        // 使用GET请求（默认行为，不需要特别设置）
        // 设置请求头
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Accept: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        // 设置响应回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);

        // 执行请求
        res = curl_easy_perform(curl);
        // 清理
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);

        if (res == CURLE_OK) {
            try {
                // 解析JSON响应
                json response_json = json::parse(response_string);
                // std::cout << "API响应内容: " << response_json.dump(4) << std::endl;
                // 检查响应码
                if (response_json["code"] == 200 && response_json.contains("data")) {
                    std::string room_id = response_json["data"]["roomId"];
                    std::string session_id = response_json["data"]["sessionId"];

                    std::cout << "成功获取房间信息:" << std::endl;
                    std::cout << "房间ID: " << room_id << std::endl;
                    std::cout << "会话ID: " << session_id << std::endl;

                    return room_id;
                } else {
                    std::cerr << "API返回错误: " << response_json["msg"] << std::endl;
                    return "";
                }
            } catch (const std::exception& e) {
                std::cerr << "JSON解析错误: " << e.what() << std::endl;
                std::cerr << "响应内容: " << response_string << std::endl;
                return "";
            }
        } else {
            std::cerr << "HTTP请求失败: " << curl_easy_strerror(res) << std::endl;
            return "";
        }
    } else {
        std::cerr << "CURL初始化失败" << std::endl;
        return "";
    }
}

// 生成消息ID
std::string WebRTC_offer::generate_message_id() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(100000, 999999);

    auto now = std::chrono::system_clock::now();
    auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();

    return "MSG_" + std::to_string(timestamp) + "_" + std::to_string(dis(gen));
}

// 获取ISO 8601格式的时间戳
std::string WebRTC_offer::get_iso8601_timestamp() {
    auto now = std::chrono::system_clock::now();
    auto time_t_now = std::chrono::system_clock::to_time_t(now);
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

    std::stringstream ss;
    ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%S");
    ss << '.' << std::setfill('0') << std::setw(3) << ms.count() << 'Z';

    return ss.str();
}

// 创建心跳消息
json WebRTC_offer::create_heartbeat_message(const std::string& room_id) {
    json heartbeat_msg;
    heartbeat_msg["type"] = "heartbeat";
    heartbeat_msg["from"] = robot_id_;
    heartbeat_msg["roomId"] = room_id;
    heartbeat_msg["timestamp"] = get_iso8601_timestamp();
    heartbeat_msg["messageId"] = generate_message_id();

    return heartbeat_msg;
}

// 心跳循环函数
void WebRTC_offer::heartbeat_loop(const std::string& room_id, const std::string& websocket_url) {
    try {
        client ws_client;

        // 设置日志级别
        ws_client.set_access_channels(websocketpp::log::alevel::all);
        ws_client.clear_access_channels(websocketpp::log::alevel::frame_payload);

        // 初始化ASIO
        ws_client.init_asio();

        // 设置TLS初始化处理器
        ws_client.set_tls_init_handler([](websocketpp::connection_hdl) {
            auto ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);
            try {
                ctx->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 |
                                 boost::asio::ssl::context::no_sslv3 | boost::asio::ssl::context::single_dh_use);
            } catch (std::exception& e) {
                std::cout << "TLS设置异常: " << e.what() << std::endl;
            }
            return ctx;
        });

        // 设置消息处理器
        ws_client.set_message_handler(
            [](websocketpp::connection_hdl, message_ptr msg) { std::cout << "收到服务器消息: " << msg->get_payload() << std::endl; });

        // 设置连接打开处理器
        ws_client.set_open_handler([](websocketpp::connection_hdl) { std::cout << "WebSocket连接已建立" << std::endl; });

        // 设置连接关闭处理器
        ws_client.set_close_handler([](websocketpp::connection_hdl) { std::cout << "WebSocket连接已关闭" << std::endl; });

        // 设置失败处理器
        ws_client.set_fail_handler([](websocketpp::connection_hdl) { std::cout << "WebSocket连接失败" << std::endl; });

        websocketpp::lib::error_code ec;
        client::connection_ptr con = ws_client.get_connection(websocket_url, ec);
        if (ec) {
            std::cout << "WebSocket连接创建失败: " << ec.message() << std::endl;
            return;
        }

        ws_client.connect(con);

        // 在单独的线程中运行WebSocket事件循环
        std::thread ws_thread([&ws_client]() { ws_client.run(); });

        // 等待连接建立
        std::this_thread::sleep_for(std::chrono::seconds(2));

        while (heartbeat_running_.load()) {
            try {
                std::lock_guard<std::mutex> lock(heartbeat_mutex_);

                // 创建心跳消息
                json heartbeat_msg = create_heartbeat_message(room_id);
                std::string heartbeat_str = heartbeat_msg.dump();

                std::cout << "发送心跳消息: " << heartbeat_str << std::endl;

                // 发送心跳消息
                websocketpp::lib::error_code send_ec;
                ws_client.send(con, heartbeat_str, websocketpp::frame::opcode::text, send_ec);
                if (send_ec) {
                    std::cout << "发送心跳消息失败: " << send_ec.message() << std::endl;
                }

            } catch (const std::exception& e) {
                std::cerr << "心跳发送异常: " << e.what() << std::endl;
            }

            // 等待10秒 (0.1Hz频率)
            std::this_thread::sleep_for(std::chrono::seconds(10));
        }

        // 关闭WebSocket连接
        ws_client.close(con, websocketpp::close::status::going_away, "");
        ws_thread.join();

    } catch (const std::exception& e) {
        std::cerr << "WebSocket心跳循环异常: " << e.what() << std::endl;
    }
}

// 启动心跳
void WebRTC_offer::start_heartbeat(const std::string& room_id, const std::string& websocket_url) {
    if (heartbeat_running_.load()) {
        std::cout << "心跳已经在运行中" << std::endl;
        return;
    }

    heartbeat_running_.store(true);
    heartbeat_thread_ = std::thread(&WebRTC_offer::heartbeat_loop, this, room_id, websocket_url);

    std::cout << "WebSocket心跳已启动，房间ID: " << room_id << std::endl;
}

// 停止心跳
void WebRTC_offer::stop_heartbeat() {
    if (heartbeat_running_.load()) {
        heartbeat_running_.store(false);
        if (heartbeat_thread_.joinable()) {
            heartbeat_thread_.join();
        }
        std::cout << "WebSocket心跳已停止" << std::endl;
    }
}

// 初始化WebRTC
void WebRTC_offer::init_webrtc() {
    rtc::InitLogger(rtc::LogLevel::Warning);

    rtc::Configuration config;
    config.iceServers.emplace_back("stun:stun.l.google.com:19302");
    peer_connection_ = std::make_shared<rtc::PeerConnection>(config);

    // 设置WebRTC回调函数
    // RDP
    peer_connection_->onLocalDescription([this](rtc::Description description) {
        std::cout << "\033[31m------------------------------" << std::endl;
        std::cout << "on localDescription type: " << description.typeString() << std::endl;
        std::cout << std::string(description) << std::endl;
        std::cout << "------------------------------\033[0m" << std::endl;

        if (description.typeString() == "offer") {
            // 创建信令消息格式
            json offer_data = create_offer_data(std::string(description));
            json send_info_msg = create_send_info_message(current_room_id_, offer_data);

            if (websocket_ && websocket_->readyState() == rtc::WebSocket::State::Open) {
                websocket_->send(send_info_msg.dump());
                std::cout << "\033[31m RDP发送成功:------ " << std::endl;
                std::cout << send_info_msg.dump(2) << "\033[0m" << std::endl;
            }
        }
    });
    // ICE
    peer_connection_->onLocalCandidate([this](rtc::Candidate candidate) {
        std::cout << "\033[33m------------------------------" << std::endl;
        std::cout << "on localCandidate: " << std::string(candidate) << std::endl;
        std::cout << "------------------------------\033[0m" << std::endl;

        // 收集ICE candidates
        {
            std::lock_guard<std::mutex> lock(ice_candidates_mutex_);
            local_ice_candidates_.push_back(std::string(candidate));
        }
    });

    peer_connection_->onStateChange([](rtc::PeerConnection::State state) { std::cout << "[WebRTC State: " << state << "]" << std::endl; });

    peer_connection_->onGatheringStateChange([this](rtc::PeerConnection::GatheringState state) {
        std::cout << "[Gathering State: " << state << "]" << std::endl;

        if (state == rtc::PeerConnection::GatheringState::Complete) {
            std::cout << "ICE gathering complete, 发送ICE candidate batch" << std::endl;
            ice_gathering_complete_.store(true);
            send_ice_candidate_batch();
        }
    });

    // 创建数据通道
    data_channel_ = peer_connection_->createDataChannel("robot_channel");
    data_channel_->onOpen([this]() {
        std::cout << "\033[32m[DataChannel open: " << data_channel_->label() << "]\033[0m" << std::endl;
        data_channel_->send("Hello from " + robot_id_);

        // 数据通道打开后，尝试加载并发送PCD文件
        std::string pcd_file_path = "../PCD/test_indoor_0513.pcd";  // 可以修改为您的PCD文件路径
        if (load_pcd_file(pcd_file_path)) {
            auto binary_data = pcd_to_binary();
            if (!binary_data.empty()) {
                std::cout << "开始通过RTC数据通道发送PCD数据..." << std::endl;
                send_binary_data_via_rtc(binary_data);
            }
        }
    });

    data_channel_->onClosed([this]() { std::cout << "\033[32m[DataChannel closed: " << data_channel_->label() << "]\033[0m" << std::endl; });

    data_channel_->onMessage([](auto data) {
        if (std::holds_alternative<std::string>(data)) {
            std::cout << "\033[32m[Received: " << std::get<std::string>(data) << "]\033[0m" << std::endl;
        }
    });
}

// 连接信令服务器
void WebRTC_offer::connect_signaling_server(const std::string& room_id) {
    current_room_id_ = room_id;
    websocket_ = std::make_shared<rtc::WebSocket>();
    std::string signaling_url =
        "wss://information-channel.cn/back-end/rt-signaling/signaling?token=valid_token&clientId=" + robot_id_ + "&clientType=HARDWARE_DEVICE";
    std::promise<void> wsPromise;
    auto wsFuture = wsPromise.get_future();

    websocket_->open(signaling_url);
    std::cout << "正在连接信令服务器..." << std::endl;

    websocket_->onOpen([&wsPromise, this]() {
        std::cout << "WebSocket连接已建立，信令服务器就绪" << std::endl;
        wsPromise.set_value();
        // 连接建立后立即发送join-room
        this->send_room_action("join-room");
    });

    websocket_->onError([&wsPromise](std::string error) {
        std::cout << "WebSocket连接错误: " << error << std::endl;
        wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(error)));
    });

    websocket_->onClosed([]() { std::cout << "WebSocket连接已关闭" << std::endl; });

    websocket_->onMessage([this](auto data) {
        if (std::holds_alternative<std::string>(data)) {
            std::string msg_str = std::get<std::string>(data);
            try {
                json msg = json::parse(msg_str);
                // 判断是否为加入房间成功响应
                if (msg.contains("type") && msg["type"] == "response" && msg.contains("code") && msg["code"] == 200 && msg.contains("message") &&
                    msg["message"] == "加入成功") {
                    std::cout << "加入房间成功: " << msg.dump(2) << std::endl;
                    // 加入房间成功后再初始化WebRTC和开始信令交换
                    this->init_webrtc();
                    this->create_webrtc_offer();
                } else {
                    // 其他信令消息处理
                    handle_websocket_message(msg_str);
                }
            } catch (const std::exception& e) {
                std::cerr << "WebSocket消息解析失败: " << e.what() << std::endl;
                std::cerr << "原始消息: " << msg_str << std::endl;
            }
        }
    });

    try {
        wsFuture.get();  // 等待连接建立
        std::cout << "信令服务器连接成功" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "信令服务器连接失败: " << e.what() << std::endl;
    }
}

// 创建WebRTC Offer
void WebRTC_offer::create_webrtc_offer() {
    if (!peer_connection_) {
        std::cerr << "PeerConnection未初始化" << std::endl;
        return;
    }

    // 这会触发onLocalDescription回调
    // peer_connection_->setLocalDescription();
    std::cout << "正在创建WebRTC Offer..." << std::endl;
}

// 创建信令消息格式
json WebRTC_offer::create_send_info_message(const std::string& room_id, const json& data) {
    json message;
    message["type"] = "send-info";
    message["from"] = robot_id_;
    message["roomId"] = room_id;
    message["timestamp"] = get_iso8601_timestamp();
    message["messageId"] = generate_message_id();
    message["data"] = data;

    return message;
}

// 创建Offer数据部分
json WebRTC_offer::create_offer_data(const std::string& offer_sdp) {
    json offer_data;
    offer_data["type"] = "offer";
    offer_data["offer"] = offer_sdp;

    return offer_data;
}

// 处理WebSocket消息
void WebRTC_offer::handle_websocket_message(const std::string& message) {
    try {
        json msg = json::parse(message);
        std::cout << "\033[34m收到信令消息: \033[0m" << msg.dump(2) << std::endl;
        std::cout << "------------------------------" << std::endl;
        if (msg.contains("type") && msg["type"] == "send-info") {
            if (msg.contains("data")) {
                json data = msg["data"];
                if (data.contains("type")) {
                    std::string data_type = data["type"];

                    if (data_type == "answer") {
                        handle_answer(data);
                    } else if (data_type == "ice-candidate-batch") {
                        handle_ice_candidate(data);
                    }
                }
            }
        }
    } catch (const std::exception& e) {
        std::cerr << "解析WebSocket消息失败: " << e.what() << std::endl;
        std::cerr << "原始消息: " << message << std::endl;
    }
}

// 处理Answer消息
void WebRTC_offer::handle_answer(const json& answer_data) {
    if (answer_data.contains("sdp")) {
        std::string answer_sdp = answer_data["sdp"];
        std::cout << "----------" << std::endl;
        std::cout << "收到Answer: " << answer_sdp << std::endl;
        std::cout << "----------" << std::endl;

        peer_connection_->setRemoteDescription(rtc::Description(answer_sdp, "answer"));
        std::cout << "Answer设置成功" << std::endl;
    }
}

// 处理ICE Candidate消息
void WebRTC_offer::handle_ice_candidate(const json& candidate_data) {
    if (candidate_data.contains("ice") && candidate_data["ice"].is_array()) {
        for (const auto& candidate : candidate_data["ice"]) {
            if (candidate.is_string()) {
                std::string candidate_str = candidate;
                std::cout << "----------" << std::endl;
                std::cout << "收到ICE Candidate: " << candidate_str << std::endl;
                std::cout << "----------" << std::endl;

                peer_connection_->addRemoteCandidate(candidate_str);
            }
        }
        std::cout << "ICE Candidate batch添加成功" << std::endl;
    }
}

// 创建ICE candidate batch数据
json WebRTC_offer::create_ice_candidate_batch_data(const std::vector<std::string>& ice_candidates) {
    json ice_data;
    ice_data["type"] = "ice-candidate-batch";
    ice_data["ice"] = ice_candidates;

    return ice_data;
}

// 发送ICE candidate batch
void WebRTC_offer::send_ice_candidate_batch() {
    std::lock_guard<std::mutex> lock(ice_candidates_mutex_);

    if (local_ice_candidates_.empty()) {
        std::cout << "没有ICE candidates需要发送" << std::endl;
        return;
    }

    json ice_batch_data = create_ice_candidate_batch_data(local_ice_candidates_);
    json send_info_msg = create_send_info_message(current_room_id_, ice_batch_data);

    std::cout << "\033[31mICE: " << send_info_msg.dump(2) << "\033[0m" << std::endl;
    if (websocket_ && websocket_->readyState() == rtc::WebSocket::State::Open) {
        websocket_->send(send_info_msg.dump());
        std::cout << "ICE candidate batch发送成功:" << std::endl;
        std::cout << send_info_msg.dump(2) << std::endl;

        // 清空已发送的candidates
        local_ice_candidates_.clear();
        // ICE发送完成后再启动心跳
        start_heartbeat(current_room_id_);
    } else {
        std::cerr << "WebSocket未连接，无法发送ICE candidate batch" << std::endl;
    }
}

// 发送房间相关动作消息（如加入房间、离开房间）
void WebRTC_offer::send_room_action(const std::string& action_type) {
    json msg;
    msg["type"] = action_type;
    msg["roomId"] = current_room_id_;
    msg["from"] = robot_id_;
    msg["timestamp"] = get_iso8601_timestamp();
    msg["messageId"] = generate_message_id();
    if (websocket_ && websocket_->readyState() == rtc::WebSocket::State::Open) {
        websocket_->send(msg.dump());
        std::cout << "已发送 " << action_type << " 消息: " << msg.dump() << std::endl;
    } else {
        std::cerr << "WebSocket未连接，无法发送 " << action_type << " 消消息" << std::endl;
    }
}

// 加载PCD文件
bool WebRTC_offer::load_pcd_file(const std::string& file_path) {
    try {
        if (pcl::io::loadPCDFile<pcl::PointXYZ>(file_path, *point_cloud_) == -1) {
            std::cerr << "无法加载PCD文件: " << file_path << std::endl;
            return false;
        }
        std::cout << "成功加载PCD文件: " << file_path << std::endl;
        std::cout << "点云包含 " << point_cloud_->width * point_cloud_->height << " 个数据点" << std::endl;
        return true;
    } catch (const std::exception& e) {
        std::cerr << "加载PCD文件异常: " << e.what() << std::endl;
        return false;
    }
}

// 将PCD转换为二进制数据
std::vector<uint8_t> WebRTC_offer::pcd_to_binary() {
    std::vector<uint8_t> binary_data;

    if (!point_cloud_ || point_cloud_->empty()) {
        std::cerr << "点云数据为空" << std::endl;
        return binary_data;
    }

    // 计算数据大小
    size_t data_size = point_cloud_->points.size() * sizeof(pcl::PointXYZ);
    binary_data.resize(data_size);

    // 复制点云数据到二进制数组
    memcpy(binary_data.data(), point_cloud_->points.data(), data_size);

    std::cout << "PCD转换为二进制数据完成，大小: " << binary_data.size() << " bytes" << std::endl;
    return binary_data;
}

// 对二进制数据进行切片
std::vector<std::vector<uint8_t>> WebRTC_offer::slice_binary_data(const std::vector<uint8_t>& data, size_t max_chunk_size) {
    std::vector<std::vector<uint8_t>> chunks;

    if (data.empty()) {
        std::cerr << "输入数据为空" << std::endl;
        return chunks;
    }

    if (data.size() > MAX_BUFFER_SIZE) {
        std::cerr << "数据大小超过缓存区上限 " << MAX_BUFFER_SIZE << " bytes" << std::endl;
        return chunks;
    }

    size_t total_size = data.size();
    size_t offset = 0;

    while (offset < total_size) {
        size_t chunk_size = std::min(max_chunk_size, total_size - offset);
        std::vector<uint8_t> chunk(data.begin() + offset, data.begin() + offset + chunk_size);
        chunks.push_back(chunk);
        offset += chunk_size;
    }

    std::cout << "数据切片完成，总大小: " << total_size << " bytes，分片数: " << chunks.size() << std::endl;
    return chunks;
}

// 创建数据包（按照协议格式）
std::vector<uint8_t> WebRTC_offer::create_data_packet(uint32_t message_id,
                                                      uint32_t index,
                                                      uint32_t total,
                                                      uint32_t data_type,
                                                      const std::vector<uint8_t>& data) {
    std::vector<uint8_t> packet;
    packet.reserve(20 + data.size());

    // Magic number: 0x637070 - 小端写入
    uint32_t magic = 0x707063;  // 'cpp' in ASCII: 'c'=0x63, 'p'=0x70, 'p'=0x70
    // Magic number - 大端写入
    packet.push_back(static_cast<uint8_t>((magic >> 24) & 0xFF));  // 高字节
    packet.push_back(static_cast<uint8_t>((magic >> 16) & 0xFF));
    packet.push_back(static_cast<uint8_t>((magic >> 8) & 0xFF));
    packet.push_back(static_cast<uint8_t>(magic & 0xFF));  // 低字节

    // Message ID - 大端写入
    packet.push_back(static_cast<uint8_t>((message_id >> 24) & 0xFF));
    packet.push_back(static_cast<uint8_t>((message_id >> 16) & 0xFF));
    packet.push_back(static_cast<uint8_t>((message_id >> 8) & 0xFF));
    packet.push_back(static_cast<uint8_t>(message_id & 0xFF));

    // Index - 大端写入
    packet.push_back(static_cast<uint8_t>((index >> 24) & 0xFF));
    packet.push_back(static_cast<uint8_t>((index >> 16) & 0xFF));
    packet.push_back(static_cast<uint8_t>((index >> 8) & 0xFF));
    packet.push_back(static_cast<uint8_t>(index & 0xFF));

    // Total - 大端写入
    packet.push_back(static_cast<uint8_t>((total >> 24) & 0xFF));
    packet.push_back(static_cast<uint8_t>((total >> 16) & 0xFF));
    packet.push_back(static_cast<uint8_t>((total >> 8) & 0xFF));
    packet.push_back(static_cast<uint8_t>(total & 0xFF));

    // Data type - 大端写入
    packet.push_back(static_cast<uint8_t>((data_type >> 24) & 0xFF));
    packet.push_back(static_cast<uint8_t>((data_type >> 16) & 0xFF));
    packet.push_back(static_cast<uint8_t>((data_type >> 8) & 0xFF));
    packet.push_back(static_cast<uint8_t>(data_type & 0xFF));

    // Data payload
    packet.insert(packet.end(), data.begin(), data.end());

    return packet;
}

// 打印数据包头部信息（用于调试）
void WebRTC_offer::print_packet_header(const std::vector<uint8_t>& packet) {
    if (packet.size() < 20) {
        std::cerr << "数据包大小不足20字节，无法解析头部" << std::endl;
        return;
    }

    // 解析头部 - 小端字节序读取
    uint32_t magic = static_cast<uint32_t>(packet[0]) | (static_cast<uint32_t>(packet[1]) << 8) | (static_cast<uint32_t>(packet[2]) << 16) |
                     (static_cast<uint32_t>(packet[3]) << 24);

    uint32_t message_id = static_cast<uint32_t>(packet[4]) | (static_cast<uint32_t>(packet[5]) << 8) | (static_cast<uint32_t>(packet[6]) << 16) |
                          (static_cast<uint32_t>(packet[7]) << 24);

    uint32_t index = static_cast<uint32_t>(packet[8]) | (static_cast<uint32_t>(packet[9]) << 8) | (static_cast<uint32_t>(packet[10]) << 16) |
                     (static_cast<uint32_t>(packet[11]) << 24);

    uint32_t total = static_cast<uint32_t>(packet[12]) | (static_cast<uint32_t>(packet[13]) << 8) | (static_cast<uint32_t>(packet[14]) << 16) |
                     (static_cast<uint32_t>(packet[15]) << 24);

    uint32_t data_type = static_cast<uint32_t>(packet[16]) | (static_cast<uint32_t>(packet[17]) << 8) | (static_cast<uint32_t>(packet[18]) << 16) |
                         (static_cast<uint32_t>(packet[19]) << 24);

    std::cout << "   📋 协议头部详情 (小端字节序):" << std::endl;
    std::cout << "      Magic Number: 0x" << std::hex << magic << std::dec;
    std::cout << "      MessageID: " << message_id << std::endl;
    std::cout << "      Index: " << index << std::endl;
    std::cout << "      Total: " << total << std::endl;
    std::cout << "      DataType: " << data_type << std::endl;
    std::cout << "      PayloadSize: " << (packet.size() - 20) << " bytes" << std::endl;
}

// 等待RTC缓存区可用
void WebRTC_offer::wait_for_buffer_available() {
    if (!data_channel_) {
        std::cerr << "数据通道未初始化" << std::endl;
        return;
    }

    size_t buffered_amount = data_channel_->bufferedAmount();
    int wait_count = 0;

    while (buffered_amount > RTC_BUFFER_THRESHOLD) {
        wait_count++;
        std::cout << "⚠️  RTC缓存区监控 #" << wait_count << ": " << (buffered_amount / 1024.0 / 1024.0) << " MB > "
                  << (RTC_BUFFER_THRESHOLD / 1024.0 / 1024.0) << " MB，等待10ms..." << std::endl;

        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        buffered_amount = data_channel_->bufferedAmount();

        // 避免无限等待，如果等待超过100次（1秒），输出警告
        if (wait_count > 100) {
            std::cout << "⚠️  缓存区持续满载超过1秒，可能存在网络问题" << std::endl;
            wait_count = 0;  // 重置计数器继续等待
        }
    }

    if (wait_count > 0) {
        std::cout << "✅ RTC缓存区恢复正常: " << (buffered_amount / 1024.0 / 1024.0) << " MB" << std::endl;
    }
}

// 通过RTC数据通道发送二进制数据
void WebRTC_offer::send_binary_data_via_rtc(const std::vector<uint8_t>& data) {
    if (!data_channel_) {
        std::cerr << "数据通道未初始化，无法发送数据" << std::endl;
        return;
    }

    // 显示初始RTC缓存区状态
    size_t initial_buffer = data_channel_->bufferedAmount();
    std::cout << "🔍 发送前RTC缓存区状态: " << (initial_buffer / 1024.0) << " KB" << std::endl;

    // 记录总体开始时间
    auto total_start_time = std::chrono::high_resolution_clock::now();

    // 对数据进行切片
    auto chunks = slice_binary_data(data, MAX_DATA_CHANNEL_SIZE);  // 减去协议头的20字节

    if (chunks.empty()) {
        std::cerr << "数据切片失败" << std::endl;
        return;
    }
    uint32_t message_id = 0;

    std::cout << "开始发送数据，消息ID: " << message_id << "，总分片数: " << chunks.size() << std::endl;
    std::cout << "协议格式: 每个数据片包含 [Magic(4字节) + MessageID(4字节) + Index(4字节) + Total(4字节) + DataType(4字节) + Data(N字节)]"
              << std::endl;
    std::cout << "========================================" << std::endl;

    // 发送每个分片
    for (size_t i = 0; i < chunks.size(); ++i) {
        // 检查并等待RTC缓存区可用
        wait_for_buffer_available();

        // 记录单个分片发送开始时间
        auto chunk_start_time = std::chrono::high_resolution_clock::now();

        // 创建数据包：每个数据片都包含完整的协议头部
        auto packet = create_data_packet(message_id, static_cast<uint32_t>(i), static_cast<uint32_t>(chunks.size()), 1, chunks[i]);

        // std::cout << "\n📦 准备发送分片 [" << i << "/" << (chunks.size()-1) << "]:" << std::endl;
        // std::cout << "   - MessageID: " << message_id << " (同一组数据共享)" << std::endl;
        // std::cout << "   - Index: " << i << " (当前分片索引)" << std::endl;
        // std::cout << "   - Total: " << chunks.size() << " (总分片数)" << std::endl;
        // std::cout << "   - DataType: 1 (点云数据)" << std::endl;
        // std::cout << "   - PayloadSize: " << chunks[i].size() << " bytes" << std::endl;
        // std::cout << "   - PacketSize: " << packet.size() << " bytes (包含20字节协议头)" << std::endl;

        // 打印协议头部的十六进制详细信息
        print_packet_header(packet);

        try {
            data_channel_->send(reinterpret_cast<const std::byte*>(packet.data()), packet.size());

            // 计算单个分片发送耗时
            // auto chunk_end_time = std::chrono::high_resolution_clock::now();
            // auto chunk_duration = std::chrono::duration_cast<std::chrono::microseconds>(chunk_end_time - chunk_start_time);

            // std::cout << "   ✅ 发送成功！耗时: " << chunk_duration.count() << " μs" << std::endl;

            // 添加小延迟避免发送过快
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        } catch (const std::exception& e) {
            std::cerr << "   ❌ 发送分片 " << i << " 失败: " << e.what() << std::endl;
        }
    }

    std::cout << "\n========================================" << std::endl;

    // 计算总体发送耗时
    auto total_end_time = std::chrono::high_resolution_clock::now();
    auto total_duration = std::chrono::duration_cast<std::chrono::milliseconds>(total_end_time - total_start_time);

    std::cout << "数据发送完成，总耗时: " << total_duration.count() << " ms" << std::endl;
    std::cout << "平均发送速率: " << (data.size() / 1024.0 / 1024.0) / (total_duration.count() / 1000.0) << " MB/s" << std::endl;
}

// 信号处理函数
void signal_handler(int signal) {
    std::cout << "\n收到终止信号 (" << signal << ")，正在安全退出..." << std::endl;
    g_running.store(false);

    if (g_webrtc_client) {
        // 发送离开房间消息
        std::cout << "发送离开房间消息..." << std::endl;
        g_webrtc_client->send_room_action("leave-room");

        // 停止心跳
        std::cout << "停止心跳..." << std::endl;
        g_webrtc_client->stop_heartbeat();

        // 等待一点时间确保消息发送完成
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

    std::cout << "程序安全退出" << std::endl;
    exit(0);
}

// 测试函数
int main() {
    std::cout << "开始测试WebRTC房间ID获取和信令功能..." << std::endl;

    // 注册信号处理函数
    signal(SIGINT, signal_handler);   // Ctrl+C
    signal(SIGTERM, signal_handler);  // 终止信号
#ifdef SIGQUIT
    signal(SIGQUIT, signal_handler);  // Ctrl+
#endif

    WebRTC_offer webrtc_client;
    g_webrtc_client = &webrtc_client;  // 设置全局指针用于信号处理

    // 第一步：获取房间ID
    std::string room_id = webrtc_client.get_room_id();
    if (room_id.empty()) {
        std::cout << "获取房间ID失败，程序退出" << std::endl;
        return -1;
    }
    std::cout << "成功获取房间ID: " << room_id << std::endl;

    // 第二步：连接信令服务器（后续流程在onMessage收到加入成功后自动完成）
    webrtc_client.connect_signaling_server(room_id);

    // 保持主线程运行，等待用户手动终止
    std::cout << "程序正在运行中，按 Ctrl+C 安全退出..." << std::endl;

    while (g_running.load()) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        // 可以在这里添加定期检查或状态输出
        static int counter = 0;
        if (++counter % 30 == 0) {  // 每30秒输出一次状态
            std::cout << "程序运行中... (运行时间: " << counter << " 秒)" << std::endl;
        }
    }

    // 清理全局指针
    g_webrtc_client = nullptr;
    std::cout << "程序正常退出" << std::endl;
    return 0;
}